<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button @click="handleOk" type="primary" :loading="confirmLoading"  :disabled="disableSubmit">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <!--        政策名称-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="政策名称">
              <a-input placeholder="不超过20字" v-decorator="['promotionName', validatorRules.promotionName]"
                       :disabled="disableSubmit" :readOnly="disableSubmit"/>
            </a-form-item>
          </a-col>
          <!--        促销时间-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="促销时间"
            >
              <a-range-picker :disabled="disableSubmit" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                              @change="timechange"
                              :disabled-date="disabledDate"
                              v-decorator="['startDate', validatorRules.startDate]" style="width:100%"/>
            </a-form-item>
          </a-col>
          <!--        状态-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="状态">
              <a-select v-decorator="['status', {initialValue:1,...validatorRules.actType}]" :disabled="disableSubmit"
                        placeholder="请选择">
                <a-select-option :value="1">
                  启用
                </a-select-option>
                <a-select-option :value="0">
                  停用
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--        促销模版-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="促销模版">
              <cn-dict-select-tag v-decorator="['promtionTemplate', {...validatorRules.conditionsType,initialValue:1,}]"
                                  dictCode="promtion_template"
                                  :triggerChange="true"
                                  :disabled="disableSubmit"
                                  placeholder="请选择"
                                  @change="selectTagChange"/>
            </a-form-item>
          </a-col>
          <!--        是否首单-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否首单">
              <a-select v-decorator="['isFirst', {initialValue:1,...validatorRules.actType}]" :disabled="disableSubmit"
                        placeholder="请选择">
                <a-select-option :value="1">
                  是
                </a-select-option>
                <a-select-option :value="0">
                  否
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--        是否叠加-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="是否叠加">
              <a-select v-decorator="['isOverlying', {initialValue:0,...validatorRules.actType}]"
                        :disabled="disableSubmit"
                        placeholder="请选择">
                <a-select-option :value="1">
                  是
                </a-select-option>
                <a-select-option :value="0">
                  否
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <!--        促销描述-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="促销描述">
              <a-textarea :disabled="disableSubmit" placeholder="不超过150字" style="min-height: 60px;margin-bottom: 0"
                          auto-size
                          v-decorator="['remarks']"/>
            </a-form-item>
          </a-col>
          <!--        促销商品-->
          <a-col :md="24" :sm="24" style="padding: 10px 0;">
            <a-col :md="5" :sm="24" style="padding: 0">
              <a-form-item
                :labelCol="{
                 xs: { span: 24 },
                 sm: { span: 10 }
                }"
                :wrapperCol="{
                xs: { span: 24 },
                sm: { span: 10 }
                }"
                style="margin: 0"
                :required="true"
                label="促销商品">
<!--                <a-button :disabled="disableSubmit" icon="plus" type="primary" @click="visitproducts('benping')"-->
<!--                          style="margin-bottom:10px">添加商品-->
<!--                </a-button>-->
                <cn-select-goods selectButtonText="添加商品"
                                 search-icon=""
                                 name="商品"
                                 :inputs="false"
                                 :queryParams="{customerCode: form.getFieldValue('custCode')}"
                                 :buttons="true"
                                 :multiple="promtionTemplates(['1'])"
                                 rowKey="goodsCode"
                                 :giveBackList="productVos"
                                 :queryConfig="queryConfig"
                                 :returnName="true"
                                 :disabled="disableSubmit"
                                 @select="selectGoodsBp"
                                 class="form-input">
                </cn-select-goods>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" style="padding: 0" v-if="!promtionTemplates(['2','3'])">
              <a-form-item
                :labelCol="{
               xs: { span: 24 },
               sm: { span: 4 }
              }"
                :wrapperCol="{}"
                style="margin: 0"
                :required="true"
                labelAlign="left"
                :label="promtionTemplates(['1'])?'组合起订限制':''">
                <a-input placeholder="最低起订数"
                         v-decorator="['groupLimit', validatorRules.groupLimit]"
                         type="number"
                         :disabled="disableSubmit"
                         :readOnly="disableSubmit"
                         style="width: 120px;margin: 0 10px"/>
                <span v-if="promtionTemplates(['1'])">
                  数量
              </span>
                <input type="hidden" v-decorator="['groupLimit']">
              </a-form-item>
            </a-col>
<!--            <a-col :md="0" :sm="0" style="padding: 0">-->
<!--              <a-form-item-->
<!--                :labelCol="{-->
<!--               xs: { span: 24 },-->
<!--               sm: { span: 4 }-->
<!--              }"-->
<!--                :wrapperCol="{}"-->
<!--                style="margin: 0"-->
<!--                :required="true"-->
<!--                labelAlign="left"-->
<!--                label="">-->
<!--                <a-input placeholder="最低起订数" v-decorator="['groupLimit', validatorRules.promotionName]" type="number"-->
<!--                         :disabled="disableSubmit" :readOnly="disableSubmit" style="width: 120px;margin: 0 10px"/>-->
<!--                {{ promtionTemplates(['1', '2']) ? '数量' : '金额' }}-->
<!--              </a-form-item>-->
<!--            </a-col>-->
            <a-col :md="20" :sm="20" :offset="2" style="padding: 0">
              <a-table
                bordered
                size="small"
                :rowKey="rowKey"
                :columns="columns"
                :dataSource="productVos"
                class="table-hint"
                :pagination="false"
              >
                <template slot="productNum" slot-scope="text,record,index">
                  <a-input-number type="number" v-model="text" :disabled="disableSubmit"
                           @change="e => numberCg(e,index,'productNum')"></a-input-number>
                </template>
                <template slot="isRebate" slot-scope="text,record,index">
                  <a-switch :checked="record.isRebate==1?true:false"
                            @change="e=> numberCg(e===true?1:0,index,'isRebate')"/>
                  <!--                <a-input type="number" v-model="text" :disabled="disableSubmit"-->
                  <!--                         @change="e => numberCg(e.target.value,record,'productNum')"></a-input>-->
                </template>
                <template slot="action" slot-scope="text,record,index">
                  <a href="javascript:;" :disabled="disableSubmit" @click="PromotinDelet(record)">删除</a>
                </template>
              </a-table>
            </a-col>
          </a-col>

          <!--        促销赠品-->
          <a-col :md="24" :sm="24" style="padding: 10px 0;" v-for="(item,index) in ruleVos" :key="index">
            <a-col :md="5" :sm="24" style="" v-if="promtionTemplates(['1'])">
              <a-form-item
                :labelCol="{
               xs: { span: 24 },
               sm: { span: 10 }
              }"
                :wrapperCol="{
              xs: { span: 24 },
              sm: { span: 10 }
              }"
                style="margin: 0"
                :required="true"
                label="促销赠品">
<!--                <a-button :disabled="disableSubmit" icon="plus" type="primary" @click="visitproducts(index)"-->
<!--                          style="margin-bottom:10px" >添加赠品-->
<!--                </a-button>-->
                <cn-select-goods selectButtonText="添加赠品"
                                 search-icon=""
                                 name="商品"
                                 :inputs="false"
                                 :queryParams="{customerCode: form.getFieldValue('custCode')}"
                                 :buttons="true"
                                 :multiple="promtionTemplates(['1'])"
                                 rowKey="goodsCode"
                                 :giveBackList="item.giftVos"
                                 :queryConfig="queryConfig"
                                 :returnName="true"
                                 :disabled="disableSubmit"
                                 @select="(e)=>selectGoodsZp(e,index)"
                                 class="form-input">
                </cn-select-goods>
              </a-form-item>
            </a-col>
            <a-col :md="2" :sm="24" v-if="promtionTemplates(['2','3'])">
              <a-form-item
                :labelCol="{
                 xs: { span: 24 },
                 sm: { span: 24 }
                }"
                :wrapperCol="{
                xs: { span: 0 },
                sm: { span: 0 }
                }"
                style="margin: 0"
                :required="true"
                label="促销规则">
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24" style="padding: 0">
              <a-form-item
                :labelCol="{
               xs: { span: 24 },
               sm: { span: 4 }
              }"
                style="margin: 0"
                :required="true"
                labelAlign="left"
                label="每购买商品满">
                <a-input placeholder="请输入数量" v-model="item.buyNum" type="number"
                         :disabled="disableSubmit" :readOnly="disableSubmit" style="width: 150px;margin: 0 10px"/>
                <span v-if="promtionTemplates(['1'])">
                 赠品{{ promtionTemplates(['1', '4']) ? '数量' : '金额' }}合计
                </span>
                <span v-if="promtionTemplates(['2'])">
                   特价(元):
                </span>
                  <span v-if="promtionTemplates(['3'])">
                   折扣:
                </span>
                <a-input-number v-if="!promtionTemplates(['3'])" placeholder="请输入" v-model="item.disNum" type="number" :min="0" :precision="promtionTemplates(['2'])?2:0"
                         :disabled="disableSubmit" :readOnly="disableSubmit" style="width: 150px;margin: 0 10px"/>
                <a-input-number v-if="promtionTemplates(['3'])" placeholder="请输入" v-model="item.disNum" type="number" :min="0" :max="10" :precision="2"
                                :disabled="disableSubmit" :readOnly="disableSubmit" style="width: 150px;margin: 0 10px"/>
              </a-form-item>
            </a-col>
            <a-col :md="5" :sm="24" style="margin-top: 5px;padding: 0;display: flex;align-items: center">
              <div style="width:24px;margin-left: 10px;">
                <a-icon type="delete" theme="twoTone"
                        v-if="index!==0"
                        style="font-size: 24px;color: red;line-height: 40px"
                        @click="handleDaleteRule(index)"/>
              </div>
              <a-button v-if="index === 0 " :disabled="disableSubmit" type="primary" @click="addruleVos"
                        style="margin-left: 10px">添加阶梯
              </a-button>
              <a-button :disabled="disableSubmit" type="primary" @click="copyruleVos(index)"
                        style="margin-left: 10px" v-if="promtionTemplates(['1','2','3','4'])">复制阶梯
              </a-button>
            </a-col>
            <a-col :md="20" :sm="20" :offset="2" class="table-hint" style="padding: 0"
                   v-if="promtionTemplates(['1'])">
              <a-table
                ref="table"
                size="small"
                bordered
                rowKey="code"
                :columns="zpColumns"
                :dataSource="item.giftVos"
                :pagination="ipagination1"
                :loading="loading"
                @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'2')"
              >
                <template slot="isSpirit" slot-scope="t,r,indexs">
                  <a-select v-model="t" :default-value="0" @change="e => selectCH(e,index,indexs)">
                    <a-select-option :value="1">
                      是
                    </a-select-option>
                    <a-select-option :value="0">
                      否
                    </a-select-option>
                  </a-select>
                </template>
                <template slot="takeRatio" slot-scope="t,r,indexs">
                  <a-input placeholder="请输入带走数量" v-model="t"
                           @input="e => spritCH(e,t,index,indexs)"
                           :disabled="disableSubmit"></a-input>
                </template>
                <template slot="identifier" slot-scope="t,r,indexs">
                  <a-input placeholder="请输入标识符" v-model="r.identifier"
                           @input="e => identifierCH(e,t,index,indexs)"
                           :disabled="disableSubmit || r.isSpirit && r.isSpirit == 1 ? false : true"></a-input>
                </template>

                <span slot="action" v-if="!disableSubmit" slot-scope="text, record,indexs">
                          <a @click.stop="productDelete(index,indexs)">删除</a>
                        </span>

              </a-table>
            </a-col>
          </a-col>

          <!--        阶梯买赠-->
<!--          <a-col :md="24" :sm="24" v-if="ruleVos.length>1">-->
<!--            <a-form-item-->
<!--              :labelCol="{-->
<!--             xs: { span: 24 },-->
<!--             sm: { span: 2 }-->
<!--            }"-->
<!--              :wrapperCol="{-->
<!--             xs: { span: 24 },-->
<!--             sm: { span: 20 }-->
<!--            }"-->
<!--              :required="true"-->
<!--              label="阶梯规则">-->
<!--              <a-radio-group v-decorator="['ruleType', {initialValue:1}]" @change="onChange" style="width: 100%"-->
<!--                             :disabled="disableSubmit">-->
<!--                <a-radio :style="radioStyle" :value="1">-->
<!--                  <span class="ladder-title">单阶梯买赠</span>-->
<!--                  <div class="ladder-text">-->
<!--                    公式说明：根据商品购买数量及金额，有且仅有一种阶梯可以被命中。<br/>-->
<!--                    例如：促销政策“满10个赠1个；满20个赠2个；满50个赠3个”，客户下单100个，总共赠送3个。-->
<!--                  </div>-->
<!--                </a-radio>-->
<!--                <a-radio :style="radioStyle" :value="2" v-if="promtionTemplates(['1','2','3','4','5'])">-->
<!--                  <span class="ladder-title">阶梯买赠</span>-->
<!--                  <div class="ladder-text">-->
<!--                    公式说明：创建若干阶梯，首先按照最大可享受优惠阶梯进行折现，剩余部分继续在阶梯中匹配，直至无法匹配为止。<br/>-->
<!--                    例如：促销政策“满10赠1；满20赠2；满50赠3”， 客户下单130个，总共赠送3x2+2x1+1x1=9个。-->
<!--                  </div>-->
<!--                </a-radio>-->
<!--                <a-radio :style="radioStyle" :value="3" v-if="promtionTemplates(['1','2','3','4','5'])">-->
<!--                  <span class="ladder-title">循环阶梯买赠</span>-->
<!--                  <div class="ladder-text">-->
<!--                    公式说明：创建若干阶梯，将购买商品的金额或数量的全额与阶梯进行匹配并求和。<br/>-->
<!--                    例如：促销政策“满10赠1；满20赠2；满50赠3”，客户下单100个，总共赠送3x2+2x5+ 1x10=26个。-->
<!--                  </div>-->
<!--                </a-radio>-->
<!--              </a-radio-group>-->
<!--            </a-form-item>-->
<!--          </a-col>-->

          <!--        控制条件-->
          <a-col :md="10" :sm="24">
            <a-form-item
              :labelCol="{
             xs: { span: 24 },
             sm: { span: 5 }
            }"
              :wrapperCol="wrapperCol"
              :required="true"
              label="控制条件">
              <a-radio-group :disabled="disableSubmit" v-decorator="['controlType', {initialValue:0}]">
                <a-radio :value="0">
                  不控制
                </a-radio>
                <a-radio :value="1">
                  控制赠品数量
                </a-radio>
                <a-radio :value="2">
                  控制金额
                </a-radio>
                <!--              <a-input :disabled="disableSubmit" type="number" style="width: 100px;height: 25px;margin-left: 2px" :min="0"-->
                <!--                       v-if="inputChose" v-model="controlCapacity" />-->
              </a-radio-group>
            </a-form-item>
          </a-col>

          <a-col :md="3" :sm="24" style="padding: 0">
            <a-form-item
              :labelCol="{
               xs: { span: 0 },
               sm: { span: 0 }
              }"
              :wrapperCol="wrapperCol">
              <a-input v-if="tiuse" :disabled="disableSubmit" type="number"
                       style="width: 100px;height: 25px;margin-left: 2px;margin-bottom:0" :min="0"
                       v-decorator="['controlCapacity', {initialValue:0}]"/>
              <input type="hidden" v-decorator="['controlCapacity']">
            </a-form-item>
            <a-form-item><input type="hidden" v-decorator="['ruleType']"></a-form-item>
          </a-col>

          <!--          政策适用范围-->
          <a-col :span="24">
            <div
              style="padding: 12px 24px;margin:12px 0;font-size: 16px;font-weight: 500;border-bottom: 1px solid #e8e8e8; border-top: 1px solid #e8e8e8">
              政策适用范围
            </div>
          </a-col>

          <a-col :span="24">
            <a-tabs default-active-key="1">
              <a-tab-pane key="1" tab="部门">
                <div style="padding:0 24px;">
                  <a-col :md="12" :sm="24">
                    <j-select-org :disabled="disableSubmit" selectButtonText="新增（包含）" :inputs="false" searchIcon=""
                                  :selectItems="orgList" @select="row=>orgSelect(row,1)"/>
                    <div style="margin-bottom: 12px"></div>
                  </a-col>
                  <a-col :md="12" :sm="24">
                    <j-select-org :disabled="disableSubmit" selectButtonText="新增（非包含）" :inputs="false" searchIcon=""
                                  @select="row=>orgSelect(row,0)"/>
                    <div style="margin-bottom: 12px"></div>
                  </a-col>
                  <a-col :md="12" :sm="24">
                    <a-table
                      ref="table"
                      size="middle"
                      bordered
                      rowKey="code"
                      :columns="orgColumns"
                      :dataSource="orgList"
                      :pagination="ipagination1"
                      :loading="loading"
                      @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'1')"
                    >
                      <span slot="action" v-if="!disableSubmit" slot-scope="text, record,index">
                        <a @click.stop='orgDeleta(index,"orgList")'>删除</a>
                      </span>
                    </a-table>
                  </a-col>
                  <a-col :md="12" :sm="24">
                    <a-table
                      ref="table"
                      size="middle"
                      bordered
                      rowKey="code"
                      :columns="orgColumns"
                      :dataSource="noOrgList"
                      :pagination="ipagination2"
                      :loading="loading"
                      @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'2')"
                    >
                      <span slot="action" v-if="!disableSubmit" slot-scope="text, record,index">
                        <a @click.stop='orgDeleta(index,"noOrgList")'>删除</a>
                      </span>
                    </a-table>
                  </a-col>
                </div>
              </a-tab-pane>
              <a-tab-pane key="2" tab="经销商" force-render>
                <div style="padding:0 24px;">
                  <a-col :md="12" :sm="24">
                    <j-select-cust :disabled="disableSubmit" selectButtonText="新增(包含)" :inputs="false"
                                   searchIcon="" @select="row=>activeSelect(row,1)"/>
                    <div style="margin-bottom: 12px"></div>
                  </a-col>
                  <a-col :md="12" :sm="24">
                    <j-select-cust :disabled="disableSubmit" selectButtonText="新增(非包含)" :inputs="false"
                                   searchIcon="" @select="row=>activeSelect(row,0)"/>
                    <div style="margin-bottom: 12px"></div>
                  </a-col>
                  <a-col :md="12" :sm="24">
                    <a-table
                      ref="table"
                      size="middle"
                      bordered
                      rowKey="code"
                      :columns="custColumns"
                      :dataSource="custList"
                      :pagination="ipagination3"
                      :loading="loading"
                      @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'3')"
                    >
                      <span slot="action" v-if="!disableSubmit" slot-scope="text, record,index">
                        <a @click.stop='custDeleta(index,"custList")'>删除</a>
                      </span>
                    </a-table>
                  </a-col>
                  <a-col :md="12" :sm="24">
                    <a-table
                      ref="table"
                      size="middle"
                      bordered
                      rowKey="code"
                      :columns="custColumns"
                      :dataSource="noCustList"
                      :pagination="ipagination4"
                      :loading="loading"
                      @change="(e1,e2,e3) =>handleTableChange(e1,e2,e3,'4')"
                    >
                      <span slot="action" v-if="!disableSubmit" slot-scope="text, record,index">
                        <a @click.stop='custDeleta(index,"noCustList")'>删除</a>
                      </span>
                    </a-table>
                  </a-col>
                </div>
              </a-tab-pane>
            </a-tabs>
          </a-col>

        </a-row>
      </a-form>
    </a-spin>

    <promotion-add @productcontact="productscontact" ref="promotionAd" :name="titles"></promotion-add>

  </j-modal>
</template>
<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import productModal from './productModal'
import { httpAction, postAction } from '@/api/manage'
import lodash, { pick } from 'lodash'
import PromotionAdd from './PromotionAdd'
import JSelectCust from '@/components/cn-select-popup/CnSelectCust'
import JSelectOrg from '@/components/cn-select-popup/JSelectOrg'
import JSelectProduct from '@/components/cn-select-popup/JSelectProduct'
import CnSelectGoods from '@comp/cn-select-popup/CnSelectGoods'
// import ActTermModal from '@views/tpm/act/modules/ActTermModal'
import VcTimePicker from 'ant-design-vue/es/vc-time-picker/TimePicker'
// import ARangePicker from 'ant-design-vue/es/date-picker/RangePicker'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import moment from 'moment'

export default {
  mixins: [PageListMixin],
  name: 'promotionModal',
  components: { JTreeSelect, productModal, PromotionAdd, JSelectCust, JSelectOrg,JSelectProduct ,CnSelectGoods},
  data() {
    return {
      displaystatus: 1,
      disableSubmit: false,
      tiuse:false,
      title: '编辑',
      model: {},
      radioStyle: {
        padding: '8px',
        display: 'block',
        height: '80px',
        width: '100%',
        lineHeight: '20px',
        wordWrap: 'break-word',
        backgroundColor: '#F2F2F2',
        margin: '5px 0',
        borderRadius: '5px'
      },
      ruleVos: [{
        count: 0,
        sortSn: 1,
        buyNum: '',
        disNum: '',
        giftVos: []
      }],

      rowKey: '',
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      },
      wrapperCol1: {
        xs: { span: 14 },
        sm: { span: 12 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      validatorRules: {
        promotionName: {
          rules: [
            { required: true, message: '请输入活动名称' }
          ]
        },
        startDate: {
          rules: [
            { required: true, message: '请输入选择活动时间' }
          ]
        },
        promotionType: {
          rules: [
            { required: true, message: '请选择促销类型' }
          ]
        },
        remarks: {
          rules: [
            { required: true, message: '请输入备注!' }
          ]
        },
        groupLimit: {
          rules: [
            { required: true, message: '请输入组合起订限制' }
          ]
        },

      },
      url: {
        add: window._CONFIG['domianDmsURL'] + '/promotion/dmsPromotion/saveOrUpdate',
        calculat: window._CONFIG['domianDmsURL'] + '/promotion/dmsPromotion/calculationProductAmount'
      },
      columns: [
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'salesModel'
        },
        {
          title: '销售单位',
          align: 'center',
          dataIndex: 'salesUnitDesc'
        },
        {
          title: '起订量',
          align: 'center',
          width: '150',
          dataIndex: 'productNum',
          scopedSlots: { customRender: 'productNum' }
        },
        {
          title: '起订类型',
          align: 'center',
          dataIndex: 'buyType',
          customRender(t, r, dex) {
            if (t == 1) {
              return '数量'
            } else if (t == 2) {
              return '金额'
            }
          }
        },
        {
          title: '标准订货价',
          align: 'center',
          dataIndex: 'marketingUnitMoney'
        },
        {
          title: '是否参与返利计算',
          align: 'center',
          width: '150',
          dataIndex: ' isRebate',
          scopedSlots: { customRender: 'isRebate' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      zpColumns: [
        {
          title: '赠品编码',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '赠品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '规格',
          align: 'center',
          dataIndex: 'salesModel'
        },
        {
          title: '销售单位',
          align: 'center',
          dataIndex: 'salesUnitDesc'
        },
        // {
        //   title: '是否必带',
        //   align: 'center',
        //   dataIndex: 'isSpirit',
        //   scopedSlots: { customRender: 'isSpirit' }
        // },
        {
          title: '带走数量',
          align: 'center',
          dataIndex: 'takeRatio',
          scopedSlots: { customRender: 'takeRatio' }
        },
        // {
        //   title: '标识符',
        //   align: 'center',
        //   dataIndex: 'identifier',
        //   scopedSlots: { customRender: 'identifier' }
        // },

        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      // 商品列表数据项
      incolumns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          fixed: 'left',
          width: 80,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '赠送数量',
          dataIndex: 'giftNum',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'giftNum' }
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' }
        }
      ],
      incolumns2: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          fixed: 'left',
          width: 80,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '购买数量',
          dataIndex: 'giftNum',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'giftNum' }
        },
        {
          title: '满减金额',
          dataIndex: 'disNum',
          align: 'center',
          // let
          customRender(t, r, index) {
            const obj = {
              children: t,
              attrs: {}
            }
            // if (index === 0) {
            //   obj.attrs.colSpan = r.length
            //   obj.attrs.rowSpan = r.length
            // } else {
            //   obj.attrs.colSpan = 0
            //   obj.attrs.rowSpan = 0
            // }
            return obj
          }
        }
      ],
      incolumns3: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          fixed: 'left',
          width: 80,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '优惠价格',
          dataIndex: 'disNum',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'disNum' }
        }
      ],
      incolumns4: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          fixed: 'left',
          width: 80,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '商品编码',
          align: 'center',
          dataIndex: 'productCode'
        },
        {
          title: '商品名称',
          align: 'center',
          dataIndex: 'productName'
        },
        {
          title: '订货金额',
          dataIndex: 'giftNum',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'giftNum' }
        },
        {
          title: '优惠金额',
          dataIndex: 'disNum',
          align: 'center',
          // let
          customRender(t, r, index) {
            const obj = {
              children: t,
              attrs: {}
            }
            // if (index === 0) {
            //   obj.attrs.colSpan = r.length
            //   obj.attrs.rowSpan = r.length
            // } else {
            //   obj.attrs.colSpan = 0
            //   obj.attrs.rowSpan = 0
            // }
            return obj
          }
        }
      ],
      start: false,
      amountStatus: false,

      productVos: [],
      // 范围参数
      orgColumns: [
        {
          title: '组织编码',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '组织名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      custColumns: [
        {
          title: '经销商编码',
          align: 'center',
          dataIndex: 'code'
        },
        {
          title: '经销商名称',
          align: 'center',
          dataIndex: 'name'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'left',
          width: 80,
          scopedSlots: {
            filterDropdown: 'filterDropdown',
            filterIcon: 'filterIcon',
            customRender: 'action'
          }
        }

      ],
      custList: [],
      orgList: [],
      noCustList: [],
      noOrgList: [],
      /* 分页参数 */
      ipagination1: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 分页参数 */
      ipagination2: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 分页参数 */
      ipagination3: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 分页参数 */
      ipagination4: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['5', '10', '20', '30'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      promtionTemplate: '1',
    }
  },
  computed: {
    promtionTemplates: function () {
      return function (list) {
        let vm = this
        return list.includes(vm.promtionTemplate + '')
      }
    }
  },
  watch: {},
  methods: {

    // 异步防抖函数
    handlerData(product, rules) {
      let _vm = this
      let timer = null
      let conditionsType = this.form.getFieldValue('conditionsType')
      if (typeof conditionsType == 'undefined') {
        conditionsType = this.model.conditionsType
      }
      console.log(conditionsType)
      clearTimeout(this.timer)
      return function () {
        _vm.timer = setTimeout(() => {
          let productSaveReqVo = product
          let ruleSaveReqVos = rules
          ruleSaveReqVos.forEach(item => {
            item.promotionType = 2
            item.conditionsType = conditionsType
            item.sortSn = item.count
          })
          let params = {
            productSaveReqVo,
            ruleSaveReqVos
          }
          _vm.confirmLoading = true
          postAction(_vm.url.calculat, params).then(res => {
            if (!res.success) {
              _vm.$message.error(res.message)
              _vm.confirmLoading = false
              return
            }
            if (res.result.length == 0) {
              _vm.confirmLoading = false
              _vm.$message.error('数据响应失败，请联系技术')
              return
            }
            let fina = res.result
            let rules = JSON.parse(JSON.stringify(_vm.rule))
            fina.forEach(item => {
              rules.forEach(items => {
                if (item.sortSn == items.count) {
                  items.giftSaveReqVos.forEach(itemss => {
                    if (itemss.productCode == item.productCode) {
                      // itemss.giftNum = item.discount
                      itemss.disNum = item.discount
                      itemss.giftNum = item.buyNum
                      _vm.confirmLoading = false
                    }
                  })
                }
              })
            })
            _vm.rule = rules
          })
        }, 2000)
      }()
    },

    numberCg(value, index, key) {
      let item = JSON.parse(JSON.stringify(this.productVos[index]))
      item[key] = value
      this.$set(this.productVos, index, item)
    },

    moment,
    add() {
      this.edit({})
    },
    edit(record, status) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.promtionTemplate = '1'
        if (record.id) {
          this.form.setFieldsValue({
            startDate: [this.model.beginDate, this.model.endDate]
          })
          this.promtionTemplate = this.model.promtionTemplate
          this.custList = this.model.scopeVos.filter(v => v.dataType == 2 && v.isContain == 1)
          this.orgList = this.model.scopeVos.filter(v => v.dataType == 1 && v.isContain == 1)
          this.noCustList = this.model.scopeVos.filter(v => v.dataType == 2 && v.isContain == 0)
          this.noOrgList = this.model.scopeVos.filter(v => v.dataType == 1 && v.isContain == 0)
          this.productVos = this.model.productVos.map(item=>Object.assign({},item,{
            goodsCode:item.productCode,
            goodsName:item.productName
          }))
          this.model.ruleVos.forEach(item=>{
            if(item.giftVos&&item.giftVos.length){
              item.giftVos = item.giftVos.map(item=>Object.assign({},item,{
                goodsCode:item.productCode,
                goodsName:item.productName
              }))
            }
          })
          this.ruleVos = this.model.ruleVos
        }
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
        this.tiuse=this.form.getFieldValue('controlType')!==0?true:false
        console.log(this.form.getFieldValue('controlType'))
      })
    },
    close() {
      this.promtionTemplate = ''
      this.ruleVos = [{
        count: 0,
        sortSn: 1,
        buyNum: '',
        disNum: '',
        giftVos: []
      }]
      this.productVos = []
      this.orgList = []
      this.custList = []
      this.noOrgList = []
      this.noCustList = []
      this.visible = false
    },
    handleOk() {
      const that = this
      if (this.productVos.length <= 0) {
        this.$message.warning('请选择促销商品！')
        return
      }
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          let formData = Object.assign(this.model, values)
          formData.productVos = this.productVos
          formData.ruleVos = this.ruleVos
          formData.beginDate = formData.startDate[0]
          formData.endDate = formData.startDate[1]
          formData.scopeVos = [
            ...this.orgList,
            ...this.custList,
            ...this.noCustList,
            ...this.noOrgList
          ]
          if (['1', '2', '3', '4'].includes(formData.promtionTemplate + '') && formData.ruleVos.length == 1) {
            formData.ruleType = 0
          }
          if (this.verify(formData)) {
            that.confirmLoading = true
            postAction(this.url.add, formData).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.handleCancel()
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            }).finally(() => {
              that.confirmLoading = false
            })
          }
        }
      })
    },

    verify(formData) {
      let flag = formData.ruleVos.some(item => !item.buyNum || !item.disNum)
      if (flag) {
        this.$message.error('请完善促销规则')
        return false
      }
      let promtionTemplateFlag = false
      if (['1'].includes(formData.promtionTemplate + '')) {
        for (let i = 0; i < formData.ruleVos.length; i++) {
          let num = 0
          for (let a = 0; a < formData.ruleVos[i].giftVos.length; a++) {
            num += Number(formData.ruleVos[i].giftVos[a].takeRatio)
          }
          if (num > 100) {
            promtionTemplateFlag = true
            break
          }
        }
      }
      if (promtionTemplateFlag) {
        this.$message.error('同一规则促销商品带走比例之和不能大于100')
        return false
      }

      return true

    },

    handleCancel() {
      this.close()
    },

    // 删除行内商品
    PromotinDelet(key) {
      const dataSources = this.productVos
      const target = dataSources.filter(item => item !== key)
      this.productVos = target
    },

    disabledDate(current) {
      return current && current < moment().subtract(1, 'days') //当天之前的不可选，不包括当天
    },
    // 添加商品传回值
    productscontact(value, values, index) {
      // 上方商品列表
      // debugger
      console.log(value)
      if (this.displaystatus == 2) {
        let that = this
        value.forEach(item => {
          let dex = that.dataSources.find(items => items.productCode == item.productCode)
          if (dex == undefined) {
            item.productNum = 1
            this.dataSources.push(item)
          } else {
            console.log('已有数据存在，请确认选择')
          }
        })
      } else {
        let that = this
        if (values == 'benping') {
          let type = this.form.getFieldValue('promtionTemplate')
          let buyType = 2
          if (type == 1 || 2 || 6 || 8) {
            buyType = 1
          }
          let list = []
          value.forEach(item => {
            item.productCode = item.goodsCode
            item.productName = item.goodsName
            let dex = that.productVos.find(items => items.productCode == item.productCode)
            if (dex == undefined) {
              item.buyType = buyType
              item.isRebate = 0
              item.productNum = 1
              list.push(item)
            } else {
              list.push(dex)
            }
          })
          this.productVos = list
          this.$message.success('添加商品成功')
          return
        } else if (typeof values == 'number') {
          // 下方商品列表
          let { ruleVos } = this
          const target = ruleVos[values]
          if (target) {
            value.forEach(item => {
              let dex = {}
              try {
                dex = target.giftVos.find(items => items.productCode == item.productCode)
              } catch (e) {
                target.giftVos = []
                dex = undefined
              }
              console.log(dex)
              if (dex == undefined) {
                item.takeRatio = 0
                item.productCode = item.goodsCode
                item.productName = item.goodsName
                target.giftVos.push(item)
                this.$message.success('添加赠品成功')
              } else {
                this.$message.info('已有数据存在，请重新选择')
              }
            })

            this.$set(this.ruleVos, ruleVos)
            console.log(this.rule)
          }

        }
      }

    },

    selectGoodsBp(value){
      let that = this
        let type = this.form.getFieldValue('promtionTemplate')
        let buyType = 1
        // if (type == 1 || 2 || 6 || 8) {
        //   buyType = 1
        // }
        let list = []
        value.forEach(item => {
          item.productCode = item.goodsCode
          item.productName = item.goodsName
          let dex = that.productVos.find(items => items.productCode == item.productCode)
          if (dex == undefined) {
            item.buyType = buyType
            item.isRebate = 0
            item.productNum = 1
            item.salesModel=item.goodsSpecifications
            item.salesUnit=item.basicUnit
            item.salesUnitDesc =item.basicUnitStr
            list.push(item)
          } else {
            list.push(dex)
          }
        })
        this.productVos = list
    },
    selectGoodsZp(value,index){
      let { ruleVos } = this
      const target = ruleVos[index]
      if (target) {
        value.forEach(item => {
          let dex = {}
          try {
            dex = target.giftVos.find(items => items.productCode == item.productCode)
          } catch (e) {
            target.giftVos = []
            dex = undefined
          }
          if (dex == undefined) {
            item.takeRatio = 0
            item.productCode = item.goodsCode
            item.productName = item.goodsName
            item.salesUnit=item.basicUnit
            item.salesUnitDesc =item.basicUnitStr
            item.salesModel=item.goodsSpecifications
            target.giftVos.push(item)
          } else {
          }
        })
        this.$set(this.ruleVos, ruleVos)
      }
    },
    visitproducts(type, index) {

      let place = this.form.getFieldValue('promotionType')
      if (type === 'benping') {
        this.$refs.promotionAd.multiple = false
      } else {
        this.$refs.promotionAd.multiple = true
      }

      this.$refs.promotionAd.edit(type, place, index)
    },

    handleTableChange(pagination, filters, sorter, key) {
      if (key == '1') {
        this.ipagination1 = pagination
      } else if (key == '2') {
        this.ipagination2 = pagination
      } else if (key == '3') {
        this.ipagination3 = pagination
      } else if (key == '4') {
        this.ipagination4 = pagination
      }
    },
    selectCH(value, index, indexs) {
      let item = JSON.parse(JSON.stringify(this.ruleVos[index].giftVos[indexs]))
      item.isSpirit = value
      // this.ruleVos[index].giftVos[indexs].isSpirit = value
      if (value === 0) {
        item.spiritRatio = undefined
        item.identifier = undefined
      }
      this.$set(this.ruleVos[index].giftVos, indexs, item)
    },

    addruleVos() {
      this.ruleVos.push({
        count: 0,
        sortSn: this.ruleVos.length + 1,
        buyNum: '',
        disNum: '',
        giftVos: []
      })
    },
    copyruleVos(index) {
      let item = JSON.parse(JSON.stringify(this.ruleVos[index]))
      item.sortSn = this.ruleVos.length + 1,
        this.ruleVos.push(item)
    },
    productDelete(index, indexs) {
      // debugger
      this.ruleVos[index].giftVos.splice(indexs, 1)
    },
    handleDaleteRule(index) {
      this.ruleVos.splice(index, 1)
    },
    orgSelect(row, isContain) {
      if (isContain === 1) {
        row.map(v => {
          let index = this['orgList'].findIndex(item => item.code == v.orgCode)
          index == -1 && this['orgList'].push({
            dataType: '1',
            isContain: isContain,
            code: v.orgCode,
            name: v.orgName
          })
        })
      } else {
        row.map(v => {
          let index = this['noOrgList'].findIndex(item => item.code == v.orgCode)
          index == -1 && this['noOrgList'].push({
            dataType: '1',
            isContain: isContain,
            code: v.orgCode,
            name: v.orgName
          })
        })
      }

    },
    activeSelect(row, isContain) {
      console.log(row, isContain)
      if (isContain === 1) {
        row.map(v => {
          let index = this['custList'].findIndex(item => item.code == v.custCode)
          index == -1 && this['custList'].push({
            dataType: '2',
            isContain: isContain,
            code: v.custCode,
            name: v.custName
          })
        })
      } else {
        row.map(v => {
          let index = this['noCustList'].findIndex(item => item.code == v.custCode)
          index == -1 && this['noCustList'].push({
            dataType: '2',
            isContain: isContain,
            code: v.custCode,
            name: v.custName
          })
        })
      }

    },
    custDeleta(index, key) {
      this[key].splice(index, 1)
    },
    orgDeleta(index, key) {
      this[key].splice(index, 1)
    },
    spritCH(e, e2, index, indexs) {
      console.log(e.target.value, e2, index)
      // identifier 标志符
      // spiritRatio 带走比例

      this.ruleVos[index].giftVos[indexs].takeRatio = e.target.value
      let a = 0
      let list = []
      // this.zpList.forEach(item =>{
      //   if(item.identifier&&item.identifier==this.zpList[index].identifier){
      //     item.spiritRatio = e.target.value
      //   }
      //   let k=list.findIndex(v=>v.identifier==item.identifier)
      //   if(k==-1||!item.identifier){
      //     list.push(item)
      //   }
      //
      // })
      // console.log(list)
      // list.forEach(item=>{
      //   let b = item.spiritRatio
      //   b ? b = b : b = 0
      //   a += b - 0
      // })
      // if(a >100){
      //   this.$message.info('输入的比例和不能大于100')
      //   if(this.zpList[index].identifier){
      //     this.zpList.forEach(item =>{
      //       if(item.identifier&&item.identifier==this.zpList[index].identifier){
      //         item.spiritRatio = undefined
      //       }
      //     })
      //   }else {
      //     this.zpList[index].spiritRatio = undefined
      //   }
      //
      // }
    },

    selectTagChange(e) {
      this.promtionTemplate = e
      this.productVos = []
      this.ruleVos = [{
        count: 0,
        sortSn: 1,
        buyNum: '',
        disNum: '',
        giftVos: []
      }]
    },

  }
}
</script>

<style scoped>
.addproduct {
  display: block;
  width: 100%;
  background-color: #FFFFFF;

}

.limitpromotion {
  width: 100%;
  background-color: #FFFFFF;
  padding: 10px 15px;
}

.overin {
  padding: 0 5%;
}

.placeDisplay {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}

.displayarar {
  border: 1px dashed #e2cef1;
  padding: 10px;
  margin: 4px 5px 0 5px;
  min-height: 96px;
  display: flex;
  flex-wrap: wrap;
}

.ladder-title {
  font-weight: 500;
  font-size: 14px;
}

.ladder-text {
  margin-top: 4px;
  font-weight: 400;
  font-size: 12px;
}


</style>
